import sys
import time

from fastapi import FastAPI, Request, APIRouter, Form
from fastapi.responses import PlainTextResponse
from core.WXBizMsgCrypt3 import WXBizMsgCrypt
import xml.etree.cElementTree as ET
import redis
import core.wechat_utils as wechat_utils
from db.database_utils import DatabaseUtils
import configparser

import os

config = configparser.ConfigParser()
config.read('core/config.properties')

corpid = config.get('weixin', 'corpid')
corpsecret = config.get('weixin', 'corpsecret')
print(corpid, corpsecret)
get_access_token = wechat_utils.get_access_token(corpid, corpsecret, "core/access_token.json")
print(str(get_access_token) + "lll")
# 获取当前路径
current_path = os.getcwd()

# 打印当前路径
print("当前路径是:", current_path)

router = APIRouter()
app = FastAPI()

# sToken = "ev6a2hEYWbaIgOnL31Yqp9c4jHlN"
# sEncodingAESKey = "Q7pmwlXHvmfItplmRWMnb7KGu72LVh8qZOmXPdmdzHc"
# sCorpID = "ww195f7d1dc767e06a"
# corpsecret = "ZNbMHigfJHbNThz0YGL1VNEhj1uXCMI--0YdxpbYVpY"

sToken = None
sEncodingAESKey = None
sCorpID = None
corpsecret = None

API_URL = "https://power-api.yingdao.com/oapi/power/v1/rest/flow/4c9d6a7e-1c0b-409b-92d1-c881461acef5/execute"
headers = {
    'Authorization': 'Bearer AP_g3VxPbKcjMEEgLGW',
    'Content-Type': 'application/json'
}

db_utils = DatabaseUtils("mysql+pymysql://root:123456@localhost:3306/weixin")


@router.get("/verify_callback_url")
def verify_callback_url(request: Request):
    query_params = request.query_params
    sVerifyMsgSig = query_params.get("msg_signature")
    sVerifyTimeStamp = query_params.get("timestamp")
    sVerifyNonce = query_params.get("nonce")
    sVerifyEchoStr = query_params.get("echostr")
    wxcpt = WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID)

    ret, sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr)
    if ret != 0:
        print("ERR: VerifyURL ret: " + str(ret))
        return {"errcode": ret}
    response = PlainTextResponse(sEchoStr)
    return response


@router.post("/verify_callback_url")
async def process_robot_message(request: Request):
    # 获取相关参数
    msg_signature = request.query_params.get('msg_signature')
    timestamp = request.query_params.get('timestamp')
    nonce = request.query_params.get('nonce')

    # 解析信息
    wxcpt = WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID)
    body = await request.body()
    body_str = body.decode('utf-8')
    ret, sMsg = wxcpt.DecryptMsg(body_str, msg_signature, timestamp, nonce)
    print("----------------------------------")

    # 解析xml
    root = ET.fromstring(sMsg)

    # 获取每个元素的值
    to_user_name = root.find('ToUserName').text
    from_user_name = root.find('FromUserName').text
    create_time = root.find('CreateTime').text
    msg_type = root.find('MsgType').text
    content = root.find('Content').text
    msg_id = root.find('MsgId').text
    agent_id = root.find('AgentID').text

    if msg_type == "text":
        content = "你发送的消息是:" + content
        print(content)

        corpid = config.get('weixin', 'corpid')
        corpsecret = config.get('weixin', 'corpsecret')
        get_access_token = wechat_utils.get_access_token(corpid, corpsecret, "/root/data/core/access_token.json")
        print(get_access_token)
        user_name = wechat_utils.get_user_info(get_access_token, from_user_name)["name"]
        query = f"""
        INSERT INTO 
        `weixin`.`message`
        (`creat_time`,`user_name`,`content`)
        VALUES
        ("{create_time}","{user_name}","{content}");"""
        db_utils.execute_insert(query)
        print(db_utils.execute_insert(query))
    else:
        content = "不是文本消息"
        print("不是文本消息")

    # 构建消息
    sRespData = f"""  
    <xml>  
       <ToUserName><![CDATA[{from_user_name}]]></ToUserName>  
       <FromUserName><![CDATA[{to_user_name}]]></FromUserName>  
       <CreateTime>{create_time}</CreateTime>  
       <MsgType><![CDATA[{"text"}]]></MsgType>  
       <Content><![CDATA[{content}]]></Content>  
    </xml>  
    """

    ret, sEncryptMsg = wxcpt.EncryptMsg(sRespData, nonce, timestamp)

    # 加密失败
    if ret != 0:
        print("ERR: EncryptMsg ret: " + str(ret))
        sys.exit(1)
    # 加密成功
    else:
        # 响应数据
        response = PlainTextResponse(sEncryptMsg)
        return response


# 配置信息录入
@router.post("/verification_config_message")
async def verification_config_message(
        url: str = Form(...),  # 必填字段，对应前端 input 的 name="url"
        token: str = Form(...),
        corpID: str = Form(...),  # 必填字段，对应前端 input 的 name="token"
        EncodingAESKey: str = Form(...)  # 必填字段，对应前端 input 的 name="EncodingAESKey"
):
    global sToken, sEncodingAESKey, sCorpID, corpsecret
    sToken = token
    sEncodingAESKey = EncodingAESKey
    sCorpID = corpID
    return {"status": "success"}


def write_to_redis(key, value, redis_db, redis_port):
    # 连接到Redis服务器
    redis_host = 'localhost'  # Redis服务器地址
    # redis_port = 6379  # Redis服务器端口
    # redis_db = 0  # Redis数据库索引

    redis_client = redis.Redis(host=redis_host, port=redis_port, db=redis_db)

    # 将数据写入Redis
    redis_client.set(key, value)

    print(f"Data '{value}' has been written to Redis with key '{key}'.")


@router.get("/messages")
async def get_messages():
    query = """
    SELECT `message`.`id`,
        `message`.`creat_time`,
        `message`.`user_name`,
        `message`.`content`
    FROM `weixin`.`message`;
    """
    result = db_utils.execute_query(query)
    # 将元组列表转换为字典列表
    result = [{'id': row[0], 'creat_time': row[1], 'user_name': row[2], 'content': row[3]} for row in result]
    return result


@router.get("/messages2")
async def get_messages(page: int = 1, size: int = 10):
    # 计算起始记录的索引
    start = (page - 1) * size

    # 构造查询语句
    query = f"""
    SELECT `message`.`id`,
        `message`.`creat_time`,
        `message`.`user_name`,
        `message`.`content`
    FROM `weixin`.`message`
    LIMIT {start}, {size};
    """

    # 执行查询
    result = db_utils.execute_query(query)

    # 将元组列表转换为字典列表
    result = [{'id': row[0], 'creat_time': row[1], 'user_name': row[2], 'content': row[3]} for row in result]

    return result


@router.get("/getRecordNum")
async def get_messages():
    # 构造查询语句
    query = f"""
    SELECT count(*) as count
    FROM `weixin`.`message`;
    """
    result = db_utils.execute_query(query)
    print(result)
    return result[0][0]


@router.get("/weworktest")
def test(request: Request):
    # print(sToken, sEncodingAESKey, sCorpID, corpsecret)
    # 处理数据
    time.sleep(2)
    return {"status": "success"}


#
if __name__ == "__main__":
    #     # 示例用法
    #     write_to_redis('my_key', 'Hello, Redis!')
    # uvicorn.run("my_fastapi:app", host="0.0.0.0", port=8000)
    corpid = config.get('weixin', 'corpid')
    corpsecret = config.get('weixin', 'corpsecret')
    print(corpid, corpsecret)
